'use strict';
var cacheStorageKey = 'SMLOCKv0-';

const CORE = ['/smartlock/','/smartlock/crypto.js','/smartlock/sw.js','/smartlock/logo.png','/smartlock/manifest.json'];

self.db = {
    read: (key, config) => {
        if (!config) {
            config = { type: 'text' };
        }
        return new Promise((resolve, reject) => {
            caches
                .match(new Request(`https://LOCALCACHE/${encodeURIComponent(key)}`))
                .then(function (res) {
                    res.text().then((text) => resolve(text));
                })
                .catch(() => {
                    resolve(null);
                });
        });
    },
    write: (key, value) => {
        return new Promise((resolve, reject) => {
            caches
                .open(`${cacheStorageKey}SwDB`)
                .then(function (cache) {
                    cache.put(
                        new Request(`https://LOCALCACHE/${encodeURIComponent(key)}`),
                        new Response(value)
                    );
                    resolve();
                })
                .catch(() => {
                    reject();
                });
        });
    },
};

function cacheFirst(request, key) {
    return caches.open(key).then((cache) => {
        return cache.match(request, { ignoreSearch: true, ignoreVary: true }).then((response) => {
            return (
                response ||
                fetch(request).then((response) => {
                    if (response.ok) cache.put(request, response.clone());
                    return response;
                })
            );
        });
    });
}

self.addEventListener('install', (e) => {
    e.waitUntil(
        caches.open(cacheStorageKey + 'Main').then(function (cache) {
            return cache.addAll(CORE);
        })
    );
    self.skipWaiting();
});

self.addEventListener('fetch', function (e) {
    e.respondWith(cacheFirst(e.request, cacheStorageKey + 'Main'));
    return;
});
self.addEventListener('activate', function (e) {
    e.waitUntil(
        caches
            .keys()
            .then((cacheNames) => {
                return Promise.all(
                    cacheNames
                        .filter((cacheNames) => {
                            return !cacheNames.startsWith(cacheStorageKey);
                        })
                        .map((cacheNames) => {
                            return caches.delete(cacheNames);
                        })
                );
            })
            .then(() => {
                return self.clients.claim();
            })
    );
});